package com.aggron.filter;

import com.aggron.common.ApplcationContextHelper;
import com.aggron.common.JsonData;
import com.aggron.common.RequestHolder;
import com.aggron.config.JwtConfig;
import com.aggron.dao.SysUserMapper;
import com.aggron.util.RenderUtil;
import com.aggron.util.StringUtils;
import com.aggron.util.jwt.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * auth认证的filter
 * @author   by liuhuan on 2018/6/5.
 */
public class AuthFilter extends OncePerRequestFilter{

    private final static String PAHT_SPERATOR="/";

    @Autowired
    private JwtConfig jwtConfig;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        if (request.getServletPath().equals(PAHT_SPERATOR+ jwtConfig.getAuth())) {
            chain.doFilter(request, response);
            return;
        }
        final String authToken = request.getHeader(jwtConfig.getTokenHeader());
        if(StringUtils.isEmpty(authToken)){

            RenderUtil.renderJson(response, JsonData.fail("token is null,please login again"));
            return ;
        }else {
            //验证token是否过期,包含了验证jwt是否正确
            boolean flag = jwtTokenUtil.isTokenExpired(authToken);
            if(flag){

                RenderUtil.renderJson(response, JsonData.fail("token is expired,please login again"));
                return ;
            }
        }
        RequestHolder.addToken(authToken);
        SysUserMapper sysUserMapper= ApplcationContextHelper.getBean("sysUserMapper",SysUserMapper.class);
        RequestHolder.addUserName( sysUserMapper.getSysUserByName(jwtTokenUtil.getUsernameFromToken(authToken)));
        RequestHolder.addRequest(request);
        chain.doFilter(request, response);
    }
}
